﻿using Core.Log;
using OpenTK.Graphics.OpenGL4;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Rendering.Buffer
{
    public struct VertexBufferLayoutElement
    {
        public int Location;
        public int Count;
        public bool IsNormalized;
        public VertexBufferLayoutElement(int location, int count, bool isNormalized = false)
        {
            Location = location; Count = count; IsNormalized = isNormalized;
        }
    }
    public struct VertexBufferLayout
    {
        public List<VertexBufferLayoutElement> Elements;
        public VertexBufferLayout()
        {
            Elements = new List<VertexBufferLayoutElement>();
        }
        public void AddELement(params VertexBufferLayoutElement[] el)
        {
            Elements.AddRange(el);
        }
    }
    public class VertexBufferObject : IDisposable
    {
        private readonly int _id;
        internal VertexBufferLayout Layout;
        public int Stride => GetStride();
        public VertexBufferObject(float[] vertices)
        {
            Layout = new VertexBufferLayout();
            _id = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.ArrayBuffer, _id);
            GL.BufferData(BufferTarget.ArrayBuffer, sizeof(float) * vertices.Length, vertices, BufferUsageHint.StaticDraw);
        }
        public void AddLayout(VertexBufferLayout layout)
        {
            Layout = layout;
        }
        private int GetStride()
        {
            int stride = 0;
            foreach (var vertexBufferLayoutElement in Layout.Elements)
            {
                stride += vertexBufferLayoutElement.Count * sizeof(float);
            }
            return stride;
        }

        public void Bind()
        {
            GL.BindBuffer(BufferTarget.ArrayBuffer, _id);
        }
        public static void UnBind()
        {
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
        }
        private void ReleaseUnmanageResources()
        {
            //GL.DeleteBuffer(_id);
        }
        public void Dispose()
        {
            ReleaseUnmanageResources();
            GC.SuppressFinalize(this);
        }
        ~VertexBufferObject()
        {
            ReleaseUnmanageResources();
        }
    }
}
